import {observable, action, runInAction, makeObservable} from 'mobx'
import { IUser, tokenInfo } from '@/api/login.ts'
import {message} from "antd";

class UserStore {
    constructor() {
        makeObservable(this, {
            user: observable,
            name: observable,
            change: action.bound,
            tokenGetInfo: action.bound
        })
    }
    user: IUser = {
        name: '',
        email: '',
        secretKey: '',
        profile: '',
        userUID: '',
        role: ''
    }
    name: string = ''
    oldProfile: string = ''
    change(info: IUser) {
        runInAction(() => {
            this.user = info
        })
    }
    tokenGetInfo() {
        if (localStorage.getItem(import.meta.env.VITE_MANAGE_TOKEN)) {
            tokenInfo().then(res => {
                if (res && res.code === 200) {
                    runInAction(() => {
                        const { name, userUID, role, secretKey, email, profile } = res.data
                        this.user = { name, userUID, role, secretKey, email, profile }
                        this.name = name
                        this.oldProfile = profile || ''
                    })
                } else {
                    message.error("异常");
                    setTimeout(() => {
                        window.location.href = '/#/login'
                    }, 100)
                }
            })
        } else {
            message.error("请先登录");
            setTimeout(() => {
                window.location.href = '/#/login'
            }, 100)
        }
    }
    changeName(name: string) {
        runInAction(() => {
            this.name = name
        })
    }
    changeUserName(name: string) {
        runInAction(() => {
            this.user.name = name
        })
    }
    changeProfile = (path: string) => {
        runInAction(() => {
            this.user.profile = path
            this.oldProfile = path || ''
        })
    }
}

export default new UserStore()